package com.ruoyi.common.utils.http;
import java.io.BufferedInputStream;  
import java.io.FileOutputStream;  
import java.io.IOException;  
import java.io.InputStream;  
import java.io.OutputStream;  
import java.net.HttpURLConnection;  
import java.net.URL;  
  
public class FileDownloader {  
  
    public static void downloadFile(String fileUrl, String saveDir) {  
        try {  
            URL url = new URL(fileUrl);  
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();  
  
            // 设置一些连接参数  
            connection.setRequestMethod("GET");  
            connection.setDoOutput(true);  
            connection.connect();  
  
            // 获取文件大小  
//            int fileSize = connection.getContentLength();  
  
            // 打开输入和输出流  
            InputStream inputStream = new BufferedInputStream(connection.getInputStream());  
            OutputStream outputStream = new FileOutputStream(saveDir);  
  
            byte[] buffer = new byte[4096];  
            int bytesRead;  
  
            // 读取数据并写入本地文件  
            while ((bytesRead = inputStream.read(buffer)) != -1) {  
                outputStream.write(buffer, 0, bytesRead);  
            }  
  
            // 关闭流  
            outputStream.close();  
            inputStream.close();  
  
            // 断开连接  
            connection.disconnect();  
  
//            System.out.println("文件下载完成。");  
  
        } catch (IOException e) {  
            e.printStackTrace();  
            System.out.println("文件下载失败。");  
        }  
    }  
  
}